<template>
  <ul class="list">
    <li
      class="item"
      v-for="key in letters"
      :key="key"
      :ref="key"
      @click="handleLetterClick"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    >{{key}}</li>
  </ul>
</template>

<script>
import { clearTimeout, setTimeout } from "timers";

export default {
  name: "CityAlphabet",
  props: {
    cities: Object
  },
  data() {
    return {
      touchStatus: false,
      startY: 0,
      height: 20,
      timer: null
    };
  },
  updated() {
    if (this.letters.length > 0) {
      let a = this.$refs[this.letters[0]][0];
      this.startY = a.offsetTop;
      this.height = a.clientHeight;
    }
  },
  methods: {
    handleLetterClick(e) {
      this.$emit("change", e.srcElement.innerText);
    },
    handleTouchStart() {
      this.touchStatus = true;
    },
    handleTouchMove(e) {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.timer = setTimeout(() => {
        const touchY = e.touches[0].clientY - 79;
        let index = Math.floor((touchY - this.startY) / this.height);
        if (index < 0) {
          index = 0;
        }
        if (index >= this.letters.length) {
          index = this.letters.length - 1;
        }
        this.$emit("change", this.letters[index]);
      }, 16);
    },
    handleTouchEnd() {
      this.touchStatus = false;
    }
  },
  computed: {
    letters() {
      const letters = [];
      if (this.cities) {
        for (var key in this.cities) {
          letters.push(key);
        }
      }
      return letters;
    }
  }
};
</script>

<style lang="stylus" scoped>
@import '~styles/variable.styl';

.list {
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: absolute;
  top: 1.58rem;
  right: 0;
  bottom: 0;
  width: 0.4rem;

  .item {
    line-height: 0.4rem;
    text-align: center;
    color: $bgColor;
  }
}
</style>